import React, { useRef, useEffect } from 'react';
import * as $3Dmol from '3dmol'; // <--- 这里是修正的关键！

const Molecule3DViewer = ({ smiles, backgroundColor = '#1a1a1a' }) => {
  const viewerRef = useRef(null);
  const glViewer = useRef(null); // 持久化viewer实例

  useEffect(() => {
    const element = viewerRef.current;
    if (!element) return;
    
    // 如果viewer实例不存在，则创建它
    if (!glViewer.current) {
        glViewer.current = $3Dmol.createViewer(element, { backgroundColor });
    } else {
        glViewer.current.setBackgroundColor(backgroundColor);
        glViewer.current.clear(); // 清除旧模型
    }

    if (!smiles) {
      glViewer.current.render();
      return;
    }
    
    // 从SMILES中移除聚合物的星号(*)，因为3D转换服务不识别它们
    const cleanedSMILES = smiles.replace(/\*/g, '');
    if (!cleanedSMILES) {
        glViewer.current.render();
        return;
    };

    const encodedSMILES = encodeURIComponent(cleanedSMILES);
    const url = `https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/${encodedSMILES}/SDF?record_type=3d`;

    fetch(url)
      .then(res => {
          if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
          return res.text();
      })
      .then(sdfData => {
        if (glViewer.current && sdfData && !sdfData.includes("PUGREST.NotFound")) {
            glViewer.current.addModel(sdfData, 'sdf');
            glViewer.current.setStyle({}, { stick: {} }); 
            glViewer.current.zoomTo();
            glViewer.current.render();
        } else {
            console.warn("未找到3D结构或SDF数据无效。")
        }
      })
      .catch(error => {
        console.error("无法获取或渲染3D模型:", error);
        if (glViewer.current) {
            glViewer.current.clear();
            glViewer.current.render();
        }
      });
      
  }, [smiles, backgroundColor]);

  return <div ref={viewerRef} style={{ width: '100%', height: '100%', position: 'relative' }} />;
};

export default Molecule3DViewer;